Using Thread.Sleep
in a test might introduce unpredictable and inconsistent results depending on the environment. Furthermore, it will
block the thread, which means the system resources are not being fully used.
<TestMethod>
Public Sub SomeTest()
Threading.Thread.Sleep(500) ' Noncompliant
' assertions...
End Sub
An alternative is a task-based asynchronous approach, using async and await.
More specifically the Task.Delay method should be
used, because of the following advantages:
- It is asynchronous: The thread will not be blocked, but instead will be reused by other operations
- It is more precise in timing the delay than
Thread.Sleep
- It can be canceled and continued, which gives more flexibility and control in the timing of your code
<TestMethod>
Public Async Function SomeTest() As Task
Await Task.Delay(500)
' assertions...
End Function
Another scenario is when some data might need to be mocked using Moq, and a delay needs to be
introduced:
<TestMethod>
Public Sub UserService_Test()
Dim UserService As New Mock(Of UserService)
Dim Expected As New User
UserService.Setup(Function(X) X.GetUserById(42)).Returns(
Function()
Threading.Thread.Sleep(500) ' Noncompliant
Return Task.FromResult(Expected)
End Function)
' assertions...
End Sub
An alternative to Thread.Sleep
while mocking with Moq
is to use ReturnsAsync
and pass the amount of time to
delay there:
<TestMethod>
Public Sub UserService_Test()
Dim UserService As New Mock(Of UserService)
Dim Expected As New User
UserService.Setup(Function(X) X.GetUserById(42)).ReturnsAsync(Expected, TimeSpan.FromMilliseconds(500))
' assertions...
End Sub